import 'package:get/get.dart';

import '../../../entity/home/home_widget_activity_entity.dart';
import '../../../utils/Tools.dart';
import '../../http/network.dart';

class DecorationCutDownActivityCtr extends GetxController {
  var activityEntity = HomeWidgetActivityEntity().obs;

  RxList activityGoodsList = [].obs;

  ///存储列表对应的时间戳信息
  var timeStamp = 0.obs;

  Future<void> getActivityComponentInfo(Map<String, dynamic> info) async {
    try {
      if (info['automatic'] == '0') {
        await _handleAutomaticMode(info);
      } else {
        await _handleManualMode(info);
      }
    } catch (e) {
      print("处理秒杀/特价/预售/拼团 信息时出错: $e");
    }
  }

// 自动模式处理
  Future<void> _handleAutomaticMode(Map<String, dynamic> info) async {
    List activityList = await _getActivityList(info);
    if (checkStatus(activityList)) {
      // 获取正在进行的活动
      print('获取正在进行的活动');
      Map<String, dynamic>? activityInfo = getDoingActivity(activityList);
      if (activityInfo['marketingId'] == null) {
        print("活动信息无效");
        return;
      }
      await _getSecKillGoods(activityInfo['marketingId'], info).then((value) {}).catchError((error) {
        print('什么牛马error   ====== $error');
      });
      ;
    } else {
      // 获取将要开始的活动
      print('获取将要开始的活动');
      Map<String, dynamic>? activityInfo = getPreActivity(activityList);
      if (activityInfo['marketingId'] == null) {
        print("活动信息无效");
        return;
      }
      print('获取将要开始的活动 $activityInfo');
      await _getSecKillGoods(activityInfo['marketingId'], info);
    }
  }

// 手动模式处理
  Future<void> _handleManualMode(Map<String, dynamic> info) async {
    //logger.i('手动获取 ===== ${info['sub_entry']}');
    if (info['sub_entry'] == null || info['sub_entry'].isEmpty) {
      print("sub_entry 数据无效");
      return;
    }

    String marketingId = info['sub_entry'][0]['marketingId'];
    await _getSecKillGoods(marketingId, info);
  }

// 获取活动商品列表的公用方法
  Future<void> _getSecKillGoods(String marketingId, Map<String, dynamic> info) async {
    try {
      Map<String, dynamic>? seckill = await getManualSecKillGoodsList(marketingId, getType(info));

      if (getType(info) == '5') {
        print('活动商品列表 seckill =====$seckill');
      }

      if (seckill == null || seckill.isEmpty) {
        Tools.showToast("活动商品列表为空");
        return;
      }

      // 处理响应数据
      _handleSecKillResponse(seckill, info);
    } catch (e) {
      print("sub_entry 数据无效");
    }
  }

// 获取活动列表，并设置超时
  Future<List> _getActivityList(Map<String, dynamic> info) async {
    try {
      return await getRecentlyActivityList(getType(info));
    } catch (e) {
      print('获取活动列表，并设置超时 $e');
      return [];
    }
  }

// 处理活动商品列表响应数据
  void _handleSecKillResponse(Map<String, dynamic>? seckill, Map<String, dynamic> info) {
    activityEntity.value = HomeWidgetActivityEntity.fromJson(seckill ?? {});
    activityGoodsList.value = seckill?['goodsList'] != null ? seckill!['goodsList']['list'] : [];
    timeStamp.value = int.parse(seckill?['endTime']) * 1000;
    activityEntity.refresh();
    activityGoodsList.refresh();
    timeStamp.refresh();
  }

// 获取活动列表信息
  Future<void> fetchActivityData(Map<String, dynamic> info) async {
    // 获取活动列表并根据条件过滤
    List activityList = await _getActivityList(info);

    // 获取正在进行中的活动
    Map<String, dynamic> doingActivity = getDoingActivity(activityList);

    // 获取预告的活动
    Map<String, dynamic> preActivity = getPreActivity(activityList);

    // 检查是否有正在进行的活动
    bool hasOngoingActivity = checkStatus(activityList);

    // 获取活动商品列表
    if (hasOngoingActivity) {
      await _getSecKillGoods(doingActivity['marketingId'], info);
    } else if (preActivity.isNotEmpty) {
      await _getSecKillGoods(preActivity['marketingId'], info);
    }
  }

// 获取进行中的活动信息
  Map<String, dynamic> getDoingActivity(List activityList) {
    return activityList.firstWhere(
      (activity) => activity['status'] == 2,
      orElse: () => {},
    );
  }

// 获取预告的活动信息，最近的第一个
  Map<String, dynamic> getPreActivity(List activityList) {
    return activityList.firstWhere(
      (activity) => activity['status'] == 3 && activity['preNotice'] == 1,
      orElse: () => {},
    );
  }

// true 表示 有活动这在继续，false 表示 没有活动或者还有待开始的活动
  bool checkStatus(List<dynamic> activityList) {
    return activityList.any((activity) => activity['status'] == 2);
  }

// 根据组件类型获取活动类型
  String getType(Map<String, dynamic> info) {
    switch (info['type']) {
      case 'groupon': //拼团
        return '4';
      case 'ump_limitdiscount': //特价
        return '5';
      case 'bargain': //砍价
        return '7';
      case 'advance_sale': //预售
        return '6';
      case 'ump_seckill': //秒杀
      default:
        return '3';
    }
  }

// 获取最近的活动列表
  Future getRecentlyActivityList(String type) async {
    return await Network.getActivityTimes(type);
  }

// 手动获取活动商品
  Future getManualSecKillGoodsList(String marketingId, String type) async {
    return await Network.manualQueryMarketingGoods(type, 1, 10, marketingId);
  }
}
